<?php
declare(strict_types=1);

namespace Jxzsxsp\WechatRobot\File;

use GuzzleHttp\Client;

class Upload
{
    protected $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%s&type=%s';
    protected $filepath;

    public function __construct($key, $filepath, $type='file')
    {
        $this->url = sprintf($this->url, $key, $type);
        $this->filepath = $filepath;
    }

    public function upload()
    {
        $client = new Client();

        $response = $client->post(
            $this->url,
            [
                'multipart' => [
                    [
                        'name' => 'media',
                        'contents' => fopen(realpath($this->filepath), 'r'),
                        'filename' => basename($this->filepath),
                    ]
                ],
                'headers' => [
                    'Content-Type' => 'application/octet-stream',
                    'timeout' => 5.0,
                ],
                'http_errors' => false,
                'verify' => false
            ]
        );
        $body = $response->getBody()->getContents();
        return json_decode($body, true);
    }
}